package com.words.config.auth;

import com.words.filter.auth.JwtAuthenticationFilter;
import com.words.service.SecurityUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true) //注解授权的开启
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    //数据库密码加密方式
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
    }

    //登录失败处理
    @Autowired
    LoginFailureHandler loginFailureHandler;

    //登录失败处理
    @Autowired
    LoginSuccessHandler loginSuccessHandler;

    //入口
    @Autowired
    JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;

    //权限不足处理
    @Autowired
    JwtAccessDeniedHandler jwtAccessDeniedHandler;

    //权限
    @Autowired
    private SecurityUserService securityUserService;

    @Bean
    JwtAuthenticationFilter jwtAuthenticationFilter() throws Exception {
        JwtAuthenticationFilter jwtAuthenticationFilter = new JwtAuthenticationFilter(authenticationManager());
        return jwtAuthenticationFilter;
    }

    //白名单
    public static final String[] URL_WHITELIST = {
                                "/user/**", "/login"};

    @Override
    protected void configure(HttpSecurity http) throws Exception {


        //http.userDetailsService(securityUserService);

        //关闭CRSF
        http.cors().and().csrf().disable()

                //登录配置
                .formLogin()
                .successHandler(loginSuccessHandler)//登陆成功处理
                .failureHandler(loginFailureHandler)//登录失败处理
                //禁用session
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                //配置拦截规则
                .and()
                .authorizeRequests() //开启登录认证,定义哪些URL需要被保护、哪些不需要被保护
                .antMatchers(URL_WHITELIST).permitAll()// 设置所有人都可以访问登录页面
                .anyRequest().authenticated() // 其他所有的请求 只需要登录即可
                //异常处理器
                .and()
                .exceptionHandling()
                .authenticationEntryPoint(jwtAuthenticationEntryPoint)//入口
                .accessDeniedHandler(jwtAccessDeniedHandler)          //权限不足处理器

                //配置自定义的过滤器
                .and()
                .addFilter(jwtAuthenticationFilter())
        ;
    }

    @Override
    //用户登录认证及权限
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(securityUserService);
    }
}

